<?php

namespace services\clinic;

use common\models\patient\Consumption;
use services\common\CommonService;
use services\common\ExcelExtendService;
use services\common\ExcelService;
use Yii;
use common\models\hospital\SectionList;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\clinic\Clinic;
use common\models\clinic\UserTreatment;
use common\models\statistics\ManageReport;
use api\modules\v1\forms\clinic\ClinicForm;
use yii\web\HttpException;

/**
 * Class ClinicService
 * @package services\clinic
 */
class ClinicService extends Service
{
    /**
     * 根据ID查找诊室信息
     *
     * @param int $id
     * @return Clinic|null
     */
    public function findById(int $id = 0): ?Clinic
    {
        return Clinic::find()->where(['id' => $id])->one();
    }

    /**
     * 查找诊室信息
     *
     * @param array $condition
     * @return Clinic|null
     */
    public function findInfo(array $condition = []): ?Clinic
    {
        $query = Clinic::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Clinic::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['id']) && $query->andWhere(['id' => $condition['id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        // indexBy
        isset($condition['indexBy']) && $query->indexBy($condition['indexBy']);

        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])->asArray()->all();
    }

    /**
     * 诊室列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = Clinic::find()->select(['*'])
            ->where([
                'status' => [Clinic::STATUS_INVALID, Clinic::STATUS_ENABLE],
                'project_id' => $params['project_id'],
            ]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['status' => SORT_DESC, 'sort' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'name' => $row['name'],
                'clinic_user' => $row['clinic_user'],
                'sort' => $row['sort'],
                'status' => $row['status'],
                'status_str' => Clinic::$statuss[$row['status']],
            ];
        }

        return $list;
    }

    /**
     * 新增诊室
     *
     * @param ClinicForm $model
     * @return array|mixed
     */
    public function create(ClinicForm $model)
    {
        try {
            // 1.新增诊室
            $clinic = new Clinic();
            $clinic->project_id = $model->project_id;
            $clinic->name = $model->name;
            $clinic->status = $model->status;
            if ($model->sort) {
                $clinic->sort = $model->sort;
            }
            if (!$clinic->save()) {
                throw new HttpException(422, $clinic->getFirstError($model));
            };

            // 删除缓存
            CommonService::baseRedis('clinic', 2);

            return ['id' => $clinic->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑诊室
     *
     * @param ClinicForm $model
     * @return array|mixed
     */
    public function edit(ClinicForm $model)
    {
        try {
            // 1.更新诊室
            $attributes = [
                'name' => $model->name,
                'status' => $model->status,
                'sort' => $model->sort,
            ];
            Clinic::updateAll($attributes, ['id' => $model->id]);

            // 2.更新经营报表快照排序
            ManageReport::updateAll(['clinic_sort' => $model->sort], ['clinic_id' => $model->id]);

            // 3.更新治疗信息诊室排序
            UserTreatment::updateAll(['clinic_sort' => $model->sort], ['clinic_id' => $model->id]);

            // 删除缓存
            CommonService::baseRedis('clinic', 2);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 删除诊室
     *
     * @param ClinicForm $model
     * @return array|mixed
     */
    public function delete(ClinicForm $model)
    {
        try {
            // 1.更新诊室
            $attributes = [
                'status' => Clinic::STATUS_DELETE,
            ];
            Clinic::updateAll($attributes, ['id' => $model->id]);

            // 删除缓存
            CommonService::baseRedis('clinic', 2);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑诊室状态
     *
     * @param ClinicForm $model
     * @return array|mixed
     */
    public function editStatus(ClinicForm $model)
    {
        try {
            // 1.更新角色
            $attributes = [
                'status' => $model->status,
                'updated_at' => time(),
            ];
            Clinic::updateAll($attributes, ['id' => $model->id]);

            // 删除缓存
            CommonService::baseRedis('clinic', 2);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 获取最大排序数
     * @return false|string|null
     * @author chenyuebin
     */
    public function getMaxSort()
    {
        return Clinic::find()
            ->select('max(sort) as max_sort')
            ->where([
                'and',
                ['status' => [Clinic::STATUS_ENABLE, Clinic::STATUS_INVALID]]
            ])
            ->scalar();
    }

    /**
     * @apiName 白友奕远诊室映射关系列表
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @return array|\yii\db\ActiveRecord[]
     */
    public function mapClinicList()
    {
        $project_id = Yii::$app->params['project_id'];
        $name_sx = ExcelService::getRedisProject($project_id);
        SectionList::$pix = $name_sx;

        $data = SectionList::find()
            ->asArray()
            ->all();

        foreach ($data as &$item) {
            $item['clinic_id_other'] = $item['clinic_id'];
            $item['button'] = false;
        }

        return $data;
    }

    /**
     * @apiName 更新白友奕远诊室映射关系
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @param $params
     * @return bool
     */
    public function mapClinicUpdate($params)
    {
        $project_id = Yii::$app->params['project_id'];

        $name_sx = ExcelService::getRedisProject($project_id);

        SectionList::$pix = $name_sx;
        $model = SectionList::findOne($params['id']);

        if ($model && $params['clinic_id'] && $params['clinic_name']) {
            $model->clinic_id = $params['clinic_id'];
            $model->clinic_name = $params['clinic_name'];

            if ($model->save()) {
                // 批量替换,消费记录中的,诊室id
                ExcelExtendService::repairConsumptionEmpty($project_id);
                return true;
            }
        }
        return false;
    }
}
